#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    setWindowFlags(Qt::WindowStaysOnTopHint);

    // 创建服务器对象
    server = new QTcpServer(this);
    // 开启监听服务
    bool result = server->listen(QHostAddress::Any,8887);
    if(result == false)
    {
        QMessageBox::critical(this,"错误",server->errorString());
        return;
    }
    else
    {
        printMessage("服务器开始监听,端口号8887");
        connect(server,SIGNAL(newConnection()),
                this,SLOT(newConnectionSlot()));
    }
}

Dialog::~Dialog()
{
    // 如果监听服务正在开启中，则关闭
    if(server->isListening())
        server->close();
    delete ui;
}

void Dialog::printMessage(QString msg)
{
    QString dt = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    ui->textBrowser->append(dt);
    ui->textBrowser->append(msg);
    ui->textBrowser->append("");
}

void Dialog::newConnectionSlot()
{
    // 获得服务器端的连接类对象
    socket = server->nextPendingConnection();
    QTextStream output(socket);
    if(list.size() == 20)
    {
        qDebug() << "聊天室满员";
        output << QString("聊天室已达人数上限，连接失败！");
        socket->close();
        return;
    }
    list.append(socket);
    // 断开连接检测的信号槽
    connect(socket,SIGNAL(disconnected()),
            this,SLOT(disconnectedSlot()));
    // 接受消息信号槽的连接
    connect(socket,SIGNAL(readyRead()),
            this,SLOT(readyReadSlot()));

    // Qt称呼对面的绿蛋为peer（伙伴）
    // 获得peer得IP地址和Port
    QString ip = socket->peerAddress().toString();
    quint16 port = socket->peerPort();
    QString text = "新连接已建立 ";
    text = text.append('\n').append("IP:") + ip.append("  Port:") + QString::number(port);
    printMessage(text);
}

void Dialog::disconnectedSlot()
{
    // 拿到发射者
    socket = (QTcpSocket*)sender();

    for(int i = 0;i<list.size();i++)
    {
        if(socket == list.at(i))
        {
            // 获得peer得IP地址和Port
            QString ip = socket->peerAddress().toString();
            quint16 port = socket->peerPort();
            QString text = "连接已断开 ";
            text = text.append('\n').append("IP:") + ip.append("  Port:") + QString::number(port);
            printMessage(text);
        }
    }
}

void Dialog::readyReadSlot()
{


    for(int i=0;i<list.size();i++)
    {
        if(list.at(i)->isReadable() && list.at(i)->bytesAvailable()>0)
        {
            qDebug() << "第" << i << "个客户端发的消息";
            // 方法一：读取所有内容
            QByteArray buffer = list.at(i)->readAll();

            for(int m=0;m<list.size();m++)
            {
                // 转发
                list.at(m)->write(buffer);
            }
        }
    }
}
